package com.jsle.financial.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.jsle.financial.domain.DocPublish;
import com.jsle.financial.domain.User;
import com.jsle.financial.service.DocService;
import com.jsle.financial.util.AJAXUtil;
import com.jsle.financial.util.Constants;
import com.jsle.financial.util.JsonUtil;
import com.jsle.financial.vo.Result;

@Controller  
@RequestMapping(value = "/file") 
public class FileController {
	private Log log = LogFactory.getLog(FileController.class);
	@Resource
	private DocService docService;
	@RequestMapping(value = "/publish.do", method = RequestMethod.POST)  
	public ModelAndView handlerUpload(@RequestParam("file") MultipartFile file,Model model,HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String fileName = WebUtils.findParameterValue(request, "fileName");
		String companyCode = WebUtils.findParameterValue(request, "companyCode");
		String forwardUrl = "";
		String json = "";
		log.info("name："+companyCode);
		log.info("上传文件："+file.getOriginalFilename());
		DocPublish doc = new DocPublish();
		doc.setCompanyCode(companyCode);
		doc.setFileName(fileName);
		//String filePath = System.getProperty("user.dir");
		String rootPath = request.getSession().getServletContext().getRealPath(File.separator +"upload" +File.separator);
		//filePath = filePath.substring(0, filePath.lastIndexOf(File.separator));
		//filePath = filePath + File.separator +"upload" +File.separator;
		File path = new File(rootPath);
		if(!path.exists()){
			path.mkdirs();
		}
		System.out.println("path:::"+path.getAbsolutePath());
		doc.setFilePath(File.separator +"upload" +File.separator + file.getOriginalFilename());
		Result result = docService.saveDoc(doc);
		try {
			if (!file.isEmpty()) {  
				this.copyFile(file.getInputStream(), file.getOriginalFilename(),path.getAbsolutePath());  
			}   
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(result!=null){
			if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
				json = "{\"success\":\"true\"}";
				forwardUrl = "console/publishDocSuccess";
			}
		}else{
			json = "{\"success\":\"false\"}";
			forwardUrl = "console/publishDocErr";
		}
		//AJAXUtil.writerJson(response,json);
		return new ModelAndView(forwardUrl);
	}
	
	/**
	 * 写文件到本地 
	 * @param in
	 * @param fileName
	 * @throws IOException
	 */
	private void copyFile(InputStream in,String fileName,String filePath) throws IOException{  
		FileOutputStream fs = new FileOutputStream(filePath + File.separator + fileName);  
		byte[] buffer = new byte[1024 * 1024];  
		int bytesum = 0;  
		int byteread = 0;  
		while ((byteread = in.read(buffer)) != -1) {  
			bytesum += byteread;  
			fs.write(buffer, 0, byteread);  
			fs.flush();  
		}  
		fs.close();  
		in.close();  
	}
	@RequestMapping(value = "/findDocs.do", method = RequestMethod.POST)  
	public void findDocs(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String json = "";
		DocPublish doc = new DocPublish();
		User user = (User)request.getSession().getAttribute("user");
		doc.setCompanyCode(user.getCompanyCode());
		try {
			Result result = docService.findDocs(doc);
			if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
				List<DocPublish> docs = (List<DocPublish>)result.getResultValue();
				json = JsonUtil.toJson(docs);
				json = "{\"success\":\"true\",\"data\":"+json+"}";
			}else{
				json = "{\"success\":\"false\"}";
			}
		} catch (IOException e) {
			json = "{\"success\":\"false\"}";
		}
		
		AJAXUtil.writerJson(response,json);
	}
	
	public DocService getDocService() {
		return docService;
	}

	public void setDocService(DocService docService) {
		this.docService = docService;
	}  

	
	
}
